<template>
  <div class="dicom-viewer">
    <!-- 顶部信息栏 -->
    <div class="top-info-bar">
      <div class="left-info">
        <div class="info-item">序列: {{ dicomImages.length }} 张</div>
      </div>
      <div class="right-info">
        <div class="patient-info">
          <div class="info-item">姓名: 张三</div>
          <div class="info-item">性别: 男</div>
          <div class="info-item">年龄: 45岁</div>
          <div class="info-item">检查1日期: 2023-10-15</div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 影像显示区域 -->
      <div class="viewer-section">
        <div class="image-display">
          <div 
            ref="dicomViewer" 
            class="dicom-canvas"
            @wheel="handleWheel"
          >
          </div>
          <div v-if="loadingImage" class="loading-overlay">
            <div class="spinner"></div>
            <p>正在加载影像...</p>
          </div>
          <div v-else-if="!currentImage" class="no-image-state">
            <div class="placeholder-icon">🖼️</div>
            <p>请选择一个影像文件</p>
          </div>
        </div>
      </div>
    </div>
      <!-- 底部信息栏 -->
      <div class="bottom-info-bar">
        <div class="left-info">
          <div class="info-item">宽: {{ imageWidth }}</div>
          <div class="info-item">高: {{ imageHeight }}</div>
        </div>
        <div class="center-info">
          <div class="progress-container">
            <span class="progress-text">{{ currentImageIndex + 1 }} / {{ dicomImages.length }}</span>
            <input
                type="range"
                min="1"
                :max="dicomImages.length"
                :value="currentImageIndex + 1"
                @input="changeImageByProgress"
                class="image-progress"
            />
          </div>
        </div>
        <div class="right-info">
<!--          <div class="info-item">缩放: {{ zoomLevel }}x</div>-->
          <div class="info-item">WW/WC: {{ windowWidth }}/{{ windowCenter }}</div>
        </div>
      </div>

      <!-- 悬浮控制面板 (移到最底部) -->
      <div class="floating-controls bottom-controls">
        <div class="control-buttons">
          <button @click="resetView" :disabled="!currentImage" class="control-btn">
            <span class="btn-icon">🔄</span>
          </button>
          <button @click="toggleInvert" :disabled="!currentImage" class="control-btn">
            <span class="btn-icon">🌓</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'wwwc' }]"
              @click="setTool('wwwc')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">🎚️</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'pan' }]"
              @click="setTool('pan')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">✋</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'zoom' }]"
              @click="setTool('zoom')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">🔎</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'length' }]"
              @click="setTool('length')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">📏</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'angle' }]"
              @click="setTool('angle')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">📐</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'ellipticalRoi' }]"
              @click="setTool('ellipticalRoi')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">⭕</span>
          </button>
          <!-- 新增工具按钮 -->
          <button
              :class="['tool-btn', { active: activeTool === 'rotate' }]"
              @click="setTool('rotate')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">🔄</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'rectangleRoi' }]"
              @click="setTool('rectangleRoi')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">⬜</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'freehandRoi' }]"
              @click="setTool('freehandRoi')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">✏️</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'bidirectional' }]"
              @click="setTool('bidirectional')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">⟷</span>
          </button>
          <button
              :class="['tool-btn', { active: activeTool === 'probe' }]"
              @click="setTool('probe')"
              :disabled="!currentImage"
          >
            <span class="tool-icon">📍</span>
          </button>

          <!-- 分屏和自动播放按钮 -->
          <button
              :class="['tool-btn', { active: isSplitScreen }]"
              @click="toggleSplitScreen"
              :disabled="!currentImage"
          >
            <span class="tool-icon">◫</span>
          </button>
          <button
              :class="['tool-btn', { active: isAutoPlay }]"
              @click="toggleAutoPlay"
              :disabled="!currentImage"
          >
            <span class="tool-icon">{{ isAutoPlay ? '⏸️' : '▶️' }}</span>
          </button>
        </div>
      </div>
  </div>
</template>

<script>
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import dicomParser from 'dicom-parser';
import cornerstoneMath from 'cornerstone-math';
import cornerstoneTools from 'cornerstone-tools';
import Hammer from 'hammerjs';

export default {
  name: 'ServerDicomViewer',
  data() {
    return {
      // 影像列表数据（默认服务器数据）
      dicomImages: [
        {
          id: 'image_1',
          name: 'image-000001.dcm',
          url: 'wadouri:http://localhost:8092/series-000001/image-000001.dcm',
          thumbnail: 'https://via.placeholder.com/50x50/4a90e2/ffffff?text=1'
        },
        {
          id: 'image_2',
          name: 'image-000002.dcm',
          url: 'wadouri:http://localhost:8092/series-000001/image-000002.dcm',
          thumbnail: 'https://via.placeholder.com/50x50/7ed321/ffffff?text=2'
        },
        {
          id: 'image_3',
          name: 'image-000003.dcm',
          url: 'wadouri:http://localhost:8092/series-000001/image-000003.dcm',
          thumbnail: 'https://via.placeholder.com/50x50/f5a623/ffffff?text=3'
        },
        {
          id: 'image_4',
          name: 'image-000004.dcm',
          url: 'wadouri:http://localhost:8092/series-000001/image-000004.dcm',
          thumbnail: 'https://via.placeholder.com/50x50/d0021b/ffffff?text=4'
        },
        {
          id: 'image_5',
          name: 'image-000005.dcm',
          url: 'wadouri:http://localhost:8092/series-000001/image-000005.dcm',
          thumbnail: 'https://via.placeholder.com/50x50/9013fe/ffffff?text=5'
        }
      ],
      currentImageIndex: 0,
      
      // 影像显示参数
      windowWidth: 400,
      windowCenter: 40,
      isInverted: false,
      activeTool: 'wwwc',
      // 添加分屏和自动播放相关数据
      isSplitScreen: false,
      isAutoPlay: false,
      autoPlayInterval: null,
      autoPlaySpeed: 1000, // 毫秒
      zoomLevel: 1.0,
      imageWidth: 512,
      imageHeight: 512,
      
      // 加载状态
      loadingImage: false,
      
      // cornerstone 相关对象
      element: null,
      cTools:null
    }
  },
  
  computed: {
    currentImage() {
      return this.dicomImages[this.currentImageIndex] || null;
    }
  },
  
  mounted() {
    this.initViewer();
    // 自动加载第一张影像
    if (this.dicomImages.length > 0) {
      this.loadImage(0);
    }
  },
  
  beforeDestroy() {
    if (this.element) {
      cornerstone.disable(this.element);
    }
  },
  
  methods: {
    // 初始化 cornerstone.js
    initViewer() {
      this.element = this.$refs.dicomViewer;
      
      if (!this.element) {
        console.error('DICOM查看器元素未找到');
        return;
      }
      
      try {
        // 启用 cornerstone
        cornerstone.enable(this.element);
        
        // 设置外部依赖
        if (cornerstoneWADOImageLoader && cornerstone && dicomParser) {
          cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
          cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
        }

        // 3. 设置 cornerstoneTools 的外部依赖
        cornerstoneTools.external.cornerstone = cornerstone;
        cornerstoneTools.external.Hammer = Hammer;
        cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
        cornerstoneTools.init({
          mouseEnabled: true,
          touchEnabled: true,
          globalToolSyncEnabled: true,    // 启用全局工具同步2
          showSVGCursors: true,           // 显示SVG光标
        });
        // 配置文字样式
        const textStyle = cornerstoneTools.toolColors;
        if (textStyle) {
          textStyle.setFillColor('rgba(255, 0, 0, 0.8)'); // 文字背景色
          textStyle.setToolColor('rgba(255, 0, 0, 0.8)'); // 文字背景色
        }
        // 使用 $nextTick 确保 DOM 更新后再添加工具
          // 添加工具
            cornerstoneTools.addTool(cornerstoneTools.PanTool);
            cornerstoneTools.addTool(cornerstoneTools.ZoomTool);
            cornerstoneTools.addTool(cornerstoneTools.WwwcTool);
            cornerstoneTools.addTool(cornerstoneTools.LengthTool);
            cornerstoneTools.addTool(cornerstoneTools.AngleTool);
            cornerstoneTools.addTool(cornerstoneTools.EllipticalRoiTool);
        // 添加新工具
        cornerstoneTools.addTool(cornerstoneTools.RectangleRoiTool);
        cornerstoneTools.addTool(cornerstoneTools.FreehandRoiTool);
        cornerstoneTools.addTool(cornerstoneTools.BidirectionalTool);
        cornerstoneTools.addTool(cornerstoneTools.ProbeTool);
        cornerstoneTools.addTool(cornerstoneTools.RotateTool);
          // 确保元素尺寸正确
          //cornerstone.resize(this.element, true);
        console.log('cornerstone.js 初始化完成');
      } catch (error) {
        console.error('初始化 cornerstone.js 失败:', error);
      }
    },
    
    // 加载并渲染DICOM影像
    async loadImage(index,flage) {
      const image = this.dicomImages[index];
      if (!image) return;
      
      this.currentImageIndex = index;
      if(!flage){
        this.loadingImage = true;
      }
      try {
        // 使用 cornerstone.js 加载影像
        const loadedImage = await cornerstone.loadImage(image.url);
        
        // 更新影像尺寸信息
        this.imageWidth = loadedImage.width;
        this.imageHeight = loadedImage.height;
        
        // 渲染影像
        this.renderImage(loadedImage);
        console.log(`成功加载影像: ${image.name}`);
        
      } catch (error) {
        console.error('加载DICOM影像失败:', error);
      } finally {
        this.loadingImage = false;
      }
    },
    
    // 渲染影像到画布
    renderImage(loadedImage) {
      if (!this.element) {
        console.error('DICOM画布元素未初始化');
        return;
      }
      
      try {
        // 显示影像
        cornerstone.displayImage(this.element, loadedImage);

        // 如果需要反转颜色
        if (this.isInverted) {
          this.applyInvert();
        }
        
        // 更新缩放级别
        const viewport = cornerstone.getViewport(this.element);
        this.zoomLevel = viewport.scale.toFixed(2);
        
        console.log('影像渲染完成');
      } catch (error) {
        console.error('影像渲染失败:', error);
      }
    },
    // 重置视图
    resetView() {
      if (!this.currentImage || !this.element) return;
      
      try {
        // 重置窗宽窗位
        this.windowWidth = 400;
        this.windowCenter = 40;
        
        // 重置反转状态
        this.isInverted = false;
        
        // 重置视口
        cornerstone.reset(this.element);
        this.zoomLevel = 1.0;
      } catch (error) {
        console.error('重置视图失败:', error);
      }
    },
    
    // 反转颜色
    toggleInvert() {
      if (!this.currentImage || !this.element) return;
      
      try {
        this.isInverted = !this.isInverted;
        this.applyInvert();
      } catch (error) {
        console.error('反转颜色失败:', error);
      }
    },
    
    // 应用窗宽窗位设置
    applyWindowing() {
      if (!this.element || !this.currentImage) return;
      
      try {
        const viewport = cornerstone.getViewport(this.element);
        viewport.voi = {
          windowWidth: parseInt(this.windowWidth),
          windowCenter: parseInt(this.windowCenter)
        };
        cornerstone.setViewport(this.element, viewport);
      } catch (error) {
        console.error('应用窗宽窗位设置失败:', error);
      }
    },
    
    // 应用颜色反转
    applyInvert() {
      if (!this.element) return;
      
      try {
        const viewport = cornerstone.getViewport(this.element);
        viewport.invert = this.isInverted;
        cornerstone.setViewport(this.element, viewport);
      } catch (error) {
        console.error('应用颜色反转失败:', error);
      }
    },
    
    // 设置当前工具
    // 设置当前工具
    setTool(toolName) {
      if (!this.currentImage || !this.element) {
        console.log('无法设置工具: 缺少图像或元素');
        return;
      }
      cornerstone.resize(this.element, true);

      // 检查工具是否存在
      const availableTools = ['pan', 'zoom', 'wwwc', 'length', 'angle', 'ellipticalRoi',
        'rotate', 'rectangleRoi', 'freehandRoi', 'bidirectional', 'probe'];
      if (!availableTools.includes(toolName)) {
        console.log('不支持的工具:', toolName);
        return;
      }

      try {
        this.activeTool = toolName;
        console.log('设置工具:', toolName);

        // 停用所有工具
        cornerstoneTools.setToolPassive('Pan');
        cornerstoneTools.setToolPassive('Zoom');
        cornerstoneTools.setToolPassive('Wwwc');
        cornerstoneTools.setToolPassive('Length');
        cornerstoneTools.setToolPassive('Angle');
        cornerstoneTools.setToolPassive('EllipticalRoi');
        cornerstoneTools.setToolPassive('Rotate');
        cornerstoneTools.setToolPassive('RectangleRoi');
        cornerstoneTools.setToolPassive('FreehandRoi');
        cornerstoneTools.setToolPassive('Bidirectional');
        cornerstoneTools.setToolPassive('Probe');

        const toolMap = {
          'pan': 'Pan',
          'zoom': 'Zoom',
          'wwwc': 'Wwwc',
          'length': 'Length',
          'angle': 'Angle',
          'ellipticalRoi': 'EllipticalRoi',
          'rotate': 'Rotate',
          'rectangleRoi': 'RectangleRoi',
          'freehandRoi': 'FreehandRoi',
          'bidirectional': 'Bidirectional',
          'probe': 'Probe'
        };

        if (toolMap[toolName]) {
          cornerstoneTools.setToolActive(toolMap[toolName], { mouseButtonMask: 1 });
        }

        console.log('工具设置完成:', toolName);
      } catch (error) {
        console.error('设置工具失败:', error);
      }
    }

    ,
    
    // 鼠标滚轮事件处理（翻页）
    handleWheel(event) {
      event.preventDefault();
      
      if (this.dicomImages.length <= 1) return;
      
      if (event.deltaY < 0) {
        // 向上滚动，显示下一张影像
        this.nextImage();
      } else {
        // 向下滚动，显示上一张影像
        this.previousImage();
      }
    },
    
    // 下一张影像
    nextImage() {
      if (this.currentImageIndex < this.dicomImages.length - 1) {
        this.loadImage(this.currentImageIndex + 1,true);
      }
    },
    
    // 上一张影像
    previousImage() {
      if (this.currentImageIndex > 0) {
        this.loadImage(this.currentImageIndex - 1,true);
      }
    },
    
    // 通过进度条改变影像
    changeImageByProgress(event) {
      const newIndex = parseInt(event.target.value) - 1;
      if (newIndex >= 0 && newIndex < this.dicomImages.length) {
        this.loadImage(newIndex);
      }
    },
    // 切换分屏显示
    toggleSplitScreen() {
      this.isSplitScreen = !this.isSplitScreen;
      // 实现分屏逻辑
      if (this.isSplitScreen) {
        // 启用分屏
        console.log('启用分屏显示');
      } else {
        // 关闭分屏
        console.log('关闭分屏显示');
      }
    },

    // 切换自动播放
    toggleAutoPlay() {
      this.isAutoPlay = !this.isAutoPlay;

      if (this.isAutoPlay) {
        // 开始自动播放
        this.startAutoPlay();
      } else {
        // 停止自动播放
        this.stopAutoPlay();
      }
    },

    // 开始自动播放
    startAutoPlay() {
      if (this.autoPlayInterval) {
        clearInterval(this.autoPlayInterval);
      }

      this.autoPlayInterval = setInterval(() => {
        this.nextImage();
      }, this.autoPlaySpeed);
    },

    // 停止自动播放
    stopAutoPlay() {
      if (this.autoPlayInterval) {
        clearInterval(this.autoPlayInterval);
        this.autoPlayInterval = null;
      }
    },

    // 调整自动播放速度
    setAutoPlaySpeed(speed) {
      this.autoPlaySpeed = speed;
      if (this.isAutoPlay) {
        this.stopAutoPlay();
        this.startAutoPlay();
      }
    }
  }
}
</script>

<style scoped>
.dicom-viewer {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #000;
  font-family: Arial, sans-serif;
  position: relative;
  color: #ffff00;
}

.top-info-bar {
  display: flex;
  justify-content: space-between;
  padding: 8px 15px;
  font-size: 12px;
  line-height: 16px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.bottom-info-bar {
  display: flex;
  justify-content: space-between;
  padding: 8px 15px;
  font-size: 12px;
  line-height: 16px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.left-info, .right-info {
  display: flex;
  flex-direction: column;
  min-width: 150px;
}

.right-info {
  text-align: right;
}

.info-item {
  white-space: nowrap;
}

.patient-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.left-info {
  flex: 1;
}

.right-info {
  flex: 1;
  text-align: right;
}

.patient-info {
  display: flex;
  justify-content: flex-end;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  margin-top: 0px;
  margin-bottom: 0px;
}

.viewer-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-display {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  position: relative;
}

.dicom-canvas {
  width: 100%;
  height: calc(100% - 55px);
  cursor: crosshair;
  touch-action: none; /* 防止触摸事件干扰 */
  user-select: none; /* 防止文本选择干扰 */
  /* 添加以下属性确保正确的坐标计算 */
  position: relative;
  display: block;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #ffff00;
  z-index: 10;
  font-size: 12px;
  line-height: 16px;
}

.loading-overlay .spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #333;
  border-top: 3px solid #ffff00;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.no-image-state {
  text-align: center;
  color: #ffff00;
  font-size: 12px;
  line-height: 16px;
}

.placeholder-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 悬浮控制面板 (放在底部) */
.floating-controls.bottom-controls {
  position: absolute;
  left: 50%;
  bottom: 0px; /* 调整位置避免与底部信息栏重叠 */
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 20px;
  padding: 5px;
  z-index: 90;
  max-width: 90vw;
}


.control-buttons {
  display: flex;
  gap: 3px;
  flex-wrap: nowrap;
  overflow-x: auto;
  padding-bottom: 5px;
}

.control-btn, .tool-btn {
  flex: 0 0 auto;
  min-width: 30px;
  padding: 6px 2px;
  background-color: rgba(100, 100, 100, 0.5);
  border: 1px solid #666;
  border-radius: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  line-height: 16px;
  color: #ffff00;
  cursor: pointer;
}

.control-btn:disabled, .tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-icon, .tool-icon {
  font-size: 14px;
  margin-bottom: 2px;
}

.tool-btn.active {
  background-color: #4a90e2;
  border-color: #4a90e2;
}

.bottom-info-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  font-size: 12px;
  line-height: 16px;
  position: absolute;
  bottom: 50px;
  left: 0;
  right: 0;
  z-index: 100;
}

.center-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-right: 20px;
  box-sizing: border-box;
}

.progress-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.progress-text {
  font-size: 12px;
  line-height: 16px;
}

.image-progress {
  width: 100%;
  height: 4px;
  -webkit-appearance: none;
  background: #333;
  border-radius: 2px;
  outline: none;
}

.image-progress::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ffff00;
  cursor: pointer;
}

.left-info, .right-info {
  min-width: 70px;
}
</style>
